﻿using System;
using System.Collections.Generic;

namespace ManoMachine.Common
{
    /// <summary>
    /// Symbols table: Associates symbols with memory addresses.
    /// </summary>
    public class SymbolsTable
    {
        readonly Dictionary<string, ushort> _symbols = new Dictionary<string, ushort>();

        /// <summary>
        /// Insert a new symbol.
        /// </summary>
        /// <param name="symbol">The symbol.</param>
        /// <param name="address">The address of the symbol.</param>
        public void Insert(string symbol, UInt16 address)
        {
            _symbols.Add(symbol.ToUpper(), address);
        }

        /// <summary>
        /// Checks the existence of the symbol.
        /// </summary>
        /// <param name="symbol"></param>
        /// <returns></returns>
        public bool Contains(string symbol)
        {
            return _symbols.ContainsKey(symbol.ToUpper());
        }

        /// <summary>
        /// Retrieve the value of a symbol if it's exists.
        /// <remarks>
        /// Null will be returned in case the symbol is not exist.
        /// </remarks>
        /// </summary>
        /// <param name="symbol">symbol</param>
        /// <returns>The memory address of the symbol if the symbol is exist</returns>
        public ushort GetAddress(string symbol)
        {
            string uSymbol = symbol.ToUpper();
            return _symbols[uSymbol];
        }

        public Dictionary<string, ushort>.Enumerator GetEnumerator()
        {
            return this._symbols.GetEnumerator();
        }

        public void Print()
        {
            ConsoleColor foregroundColor = Console.ForegroundColor;
            bool color = false;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine();
            Console.WriteLine("Symbols Table");
            foreach (KeyValuePair<string, ushort> keyValuePair in _symbols)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write(keyValuePair.Key.PadRight(5));
                Console.ForegroundColor = color ? ConsoleColor.White : ConsoleColor.Gray;
                color = !color;
                Console.WriteLine(keyValuePair.Value);
            }
            Console.ForegroundColor = foregroundColor;
        }
    }
}
